<template>
	<div class="home_box">
		<card title="快捷入口">
			<template #topCenter></template>
			<template #topRight>
				<div style="cursor: pointer">
					<div v-if="entranType" @click="chengUp">入口设置></div>
					<div v-else @click="save">完成</div>
				</div>
			</template>
			<div class="entrance">
				<!-- 显示 -->
				<div class="showItem" v-if="entranType">
					<div class="ent_item" v-for="(item, index) in myEntrance" :key="index" :style="changeStyle(item.level)" @click="toPage(item)">
						<div>
							<div class="text">{{ item.name }}</div>
						</div>
						<div>
							<el-icon :style="changeStyle(item.level)"><ArrowRightBold /></el-icon>
						</div>
					</div>
				</div>
				<div v-if="myEntrance.length == 0 && entranType">暂无快捷入口，请添加</div>
				<!-- 添加删除 -->
				<div class="updataItem" v-if="!entranType">
					<div class="ent_item" v-for="(item, index) in updataEntrance" :key="index" :style="changeStyle(item.level)">
						<div class="text">{{ item.name }}</div>
						<el-icon class="icon" @click="delItem(index)"><CircleClose /></el-icon>
					</div>
					<el-icon class="ent_item_add" @click="deta.centerDialogVisible = true"><Plus /></el-icon>
				</div>
				<div></div>
			</div>
		</card>

		<div class="box_bottom">
			<div class="left" v-if="toDoing || toDoed">
				<card title="待办管理">
					<div class="content_left">
						<div class="item" v-if="toDoing">
							<img class="home_img" :src="home1" alt="" />
							<div class="text">
								待办数量&nbsp;<span class="num" :style="{ fontFamily: 'logo-title' }">{{ dataNum?.pendingNum || '--' }}</span
								>&nbsp;条
							</div>
							<div class="data" @click="toMore">
								<el-icon style="color: #afb0b3"><ArrowRightBold /></el-icon>
							</div>
						</div>
						<div class="item" v-if="toDoed">
							<img class="home_img" :src="home2" alt="" />
							<div class="text">
								已办数量&nbsp;<span class="num" :style="{ fontFamily: 'logo-title' }">{{ dataNum?.completedNum || '--' }}</span
								>&nbsp;条
							</div>
							<div class="data" @click="toMored">
								<el-icon style="color: #afb0b3"><ArrowRightBold /></el-icon>
							</div>
						</div>
					</div>
				</card>
			</div>
			<div class="right">
				<card title="待办列表" v-if="toDoing">
					<template #topRight>
						<div style="cursor: pointer" @click="toMore">查看更多></div>
					</template>
					<div class="content_right" v-loading="listLoading">
						<div v-if="itemList.length > 0" class="item" v-for="(item, index) in itemList" :key="index" @click="handleDeal(item)">
							<div class="left"></div>
							<div class="right">
								<span class="top_le">{{ item.paramMap.appName ? item.paramMap.appName : '--' }}</span
								><span class="top_rig">{{ item.processName }}</span>
								<div class="time">{{ item.taskCreateTime }}</div>
							</div>
						</div>
						<div v-else>暂无待办任务</div>
					</div>
				</card>
			</div>
		</div>
		<el-dialog v-model="deta.centerDialogVisible" title="快捷入口设置" width="500" align-center>
			<div style="margin-left: 50px; display: flex; align-items: center">
				<div style="margin-right: 5px">菜单名称</div>
				<el-cascader
					ref="cascaderRef"
					:placeholder="chooseItem.name"
					:options="state.menuList"
					:props="optionProps"
					:show-all-levels="false"
					@change="handleChange"
				>
					<template #default="{ node, data }">
						<span>{{ getName(data, $t(data.name)) }}</span>
					</template>
				</el-cascader>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="deta.centerDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="getUrl"> 确定 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import home1 from '/@/assets/home_tow.png';
import home2 from '/@/assets/home_one.png';
import { ElMessage } from 'element-plus';
import card from './components/Card.vue';
import { adminMenu, queryTaskDataByGroupName, iconAll, iconEdit } from '/@/api/home/home.ts';
import { queryTask, queryTaskPage } from '/@/api/stagings/index.ts';
import { storeToRefs } from 'pinia';
import mittBus from '/@/utils/mitt';
import { useThemeConfig } from '/@/stores/themeConfig';
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
import { useRoutesList } from '/@/stores/routesList';
const stores = useRoutesList();
const { routesList } = storeToRefs(stores);
import { useRouter } from 'vue-router';
import { CircleClose } from '@element-plus/icons-vue';
import { useJump } from '/@/views/stagings/useRouterJump';
const router = useRouter();
import { toRefs, defineProps, reactive, ref, onMounted, onBeforeMount, getCurrentInstance, watch } from 'vue';

onMounted(() => {
	getMyEntrance();
	getGroupName();
	setFilterRoutes();
	getMyItemList();
});
const deta = ref({
	centerDialogVisible: false,
});
const state: any = reactive({
	menuList: [],

	menuLists: [], //扁平化后的导航栏结构
});
//显示
const optionProps = {
	value: 'id',
	label: 'name',
	children: 'children',
};
//获取路由
const getRouter = () => {
	adminMenu().then((res) => {
		state.menuList = res.data;
	});
};
//改变添加路由时的名称
function getName(data: any, name: any) {
	data.name = name;
	return name;
}
//=====================
// 页面加载前
onBeforeMount(() => {
	setFilterRoutes();
	// 此界面不需要取消监听(mittBus.off('setSendColumnsChildren))
	// 因为切换布局时有的监听需要使用，取消了监听，某些操作将不生效
	mittBus.on('setSendColumnsChildren', (res: MittMenu) => {
		state.menuList = res.children;
	});
	mittBus.on('setSendClassicChildren', (res: MittMenu) => {
		let { layout, isClassicSplitMenu } = themeConfig.value;
		if (layout === 'classic' && isClassicSplitMenu) {
			state.menuList = [];
			state.menuList = res.children;
		}
	});
	mittBus.on('getBreadcrumbIndexSetFilterRoutes', () => {
		setFilterRoutes();
	});
	// mittBus.on('layoutMobileResize', (res: LayoutMobileResize) => {
	// 	closeLayoutAsideMobileMode();
	// });
});
// 设置/过滤路由（非静态路由/是否显示在菜单中）
const setFilterRoutes = () => {
	if (themeConfig.value.layout === 'columns') return false;
	state.menuList = filterRoutesFun(routesList.value);

	//深拷贝一份菜单做数据扁平化，用作快捷入口的权限控制
	let menuJson = JSON.parse(JSON.stringify(state.menuList));
	state.menuLists = treeToArray(menuJson);
	myWorkAble(state.menuList);
};
//设置我的工作台权限
const workItem = ref({
	children: [],
});
const toDoing = ref(false); //待办
const toDoed = ref(false); //已办
const myWorkAble = (data: any) => {
	data.forEach((item: any, index: any) => {
		if (item.path == '/stagings') {
			workItem.value = item;
			return;
		} else if (item.children) {
			myWorkAble(item.children);
		} else {
			return;
		}
	});
	nextTick(() => {
		getWorkItem();
	});
};
const getWorkItem = () => {
	if (workItem?.value?.children?.length == 0) {
		toDoing.value = false;
		toDoed.value = false;
	} else {
		let arr1 = workItem?.value?.children;
		arr1.forEach((item: any, index: any) => {
			if (item.path && item.path == '/stagings/schedule/index') {
				toDoing.value = true;
			}
			if (item.path && item.path == '/stagings/matters/index') {
				toDoed.value = true;
			}
		});
	}
};
// 路由过滤递归函数
const filterRoutesFun = (arr: any): any => {
	return arr
		.filter((item: any) => !item.meta?.isHide)
		.map((item: any) => {
			item = Object.assign({}, item);
			if (item.children) item.children = filterRoutesFun(item.children);
			return item;
		});
};
//样式改变
const changeStyle = (level: any) => {
	if (level == 1) {
		return { color: '#262634' };
	} else {
		return { color: '#FFFFFF !important', backgroundColor: '#5450f3' };
	}
};

//======================

//获取数据
const dataNum: any = ref({});
const getGroupName = () => {
	let data = { groupName: 'irs-pmgt' };
	queryTaskDataByGroupName(data).then((res) => {
		dataNum.value = res.data;
	});
};

//选择菜单========================
const cascaderRef: any = ref();
//选中项
const chooseItem: any = ref({
	path: '/home',
	name: '首页',
	meta: { icon: 'iconfont icon-shouye' },
	parentId: -1,
});
const handleChange = () => {
	chooseItem.value = cascaderRef.value.getCheckedNodes()[0].data;
};
//添加路由
const getUrl = () => {
	let arr: any = updataEntrance.value.map((item: any, index: any) => {
		return item.path;
	});
	let tag = arr.indexOf(chooseItem.value.path);
	if (tag != -1) {
		ElMessage({
			message: '您已添加过此模块,请重新选择',
			type: 'warning',
		});
		return;
	}
	let level = null;
	if (chooseItem.value.parentId > 0) {
		level = 1;
	} else {
		level = 0;
	}
	let data = {
		path: chooseItem.value.path,
		icon: chooseItem.value.meta.icon || '',
		name: chooseItem.value.name,
		level: level,
	};
	updataEntrance.value.unshift(data);
	deta.value.centerDialogVisible = false;
};

const entranType = ref(true);
//修改
const chengUp = () => {
	entranType.value = !entranType.value;
	updataEntrance.value = myEntrance.value;
};
//删除
const delItem = (index: number) => {
	updataEntrance.value.splice(index, 1);
};
//保存
const save = () => {
	let data = updataEntrance.value;
	iconEdit(data).then((res) => {
		if (res.code == 0) {
			getMyEntrance();
			entranType.value = !entranType.value;
			updataEntrance.value = [];
		}
	});
};
const myEntrance: any = ref([]);
//获取我的快捷数据
const getMyEntrance = () => {
	iconAll().then((res) => {
		if (res.code == 0) {
			myEntrance.value = [];
			//当没有工作台权限时要过滤掉已添加过的工作台模块
			let munsPath = state.menuLists.map((ite: any) => {
				return ite.path;
			}); //提取所有的路由
			res.data.forEach((item: any, index: any) => {
				if (munsPath.indexOf(item.path) >= 0) {
					myEntrance.value.push(item);
				}
			});
		}
	});
};
//通过菜单栏过滤权限变更后的快捷入口
const filterEntrance = () => {};
function treeToArray(treeNodes: any) {
	let result: any = [];

	//递归函数 traverse，用于处理单个节点
	function traverse(node: any) {
		const newNode = { ...node };
		delete newNode.children;
		// 将没有子节点的新节点添加到结果数组中
		result.push(newNode);

		// 如果当前节点包含 children 属性（即有子节点）
		if (node.children) {
			node.children.forEach(traverse);
		}
	}

	treeNodes.forEach(traverse);

	return result;
}

//=================
const updataEntrance: any = ref([]);
const toPage = (item: any) => {
	router.push({
		path: item.path,
	});
};

const listLoading = ref(false);
const itemList: any = ref([]);
//待办列表
const getMyItemList = () => {
	listLoading.value = true;
	let data = {
		current: '1',
		size: '10',
		queryType: 1,
		groupName: 'irs-pmgt',
	};
	queryTaskPage(data)
		.then((res) => {
			if (res.code == 0) {
				itemList.value = res.data.records;
				listLoading.value = false;
			}
		})
		.catch((res) => {
			listLoading.value = false;
		});
};
//查看更多
const toMore = () => {
	router.push({
		path: '/stagings/schedule/index',
	});
};
//跳已办
const toMored = () => {
	router.push({
		path: '/stagings/matters/index',
	});
};
const { toAreaDigital, toDetail, toThreeList, toNumDetail, toAppDetail, toInfoDetail, toExpertDetail } = useJump(router);
const handleDeal = (row: any) => {
	const routeUrl = row.routeConfig?.routeUrl; //跳转路由
	const id = row.paramMap?.declareId; //业务详情id
	if (routeUrl) {
		if (routeUrl.indexOf('areaDigitalApp') > -1) {
			//区县
			toAreaDigital(row);
		} else if (routeUrl.indexOf('threeList') > -1) {
			//三张清单
			toThreeList(row, null);
		} else if (routeUrl.indexOf('operate') > -1) {
			//专家库
			toExpertDetail(row, null);
		} else if (routeUrl.indexOf('digitalList') > -1) {
			//数字化应用申报
			toNumDetail(row, 1);
		} else if (routeUrl.indexOf('digitalImplement') > -1) {
			//数字化实施
			toAppDetail(row, 1);
		} else if (routeUrl.indexOf('fileEdit') > -1) {
			//资料修改流程
			toInfoDetail(row, null);
		} else {
			ElMessage.error('路由配置错误');
		}
	} else {
		ElMessage.error('暂无详情');
	}
};
</script>

<style lang="scss" scoped>
.home_box {
	padding: 0px 20px;
	.entrance {
		.showItem {
			display: flex;
			flex-wrap: wrap;
			.ent_item {
				cursor: pointer;
				margin-right: 20px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				min-width: 150px;
				border: 1px solid #262634;
				padding: 15px 5px;
				border-radius: 4px;
				margin-bottom: 10px;
				width: 200px;
				height: 64px;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				.img {
					width: 80px;
					height: 80px;
					border: 1px solid #999999;
					border-radius: 5px;
					font-size: 45px !important;
					justify-content: center;
					margin: auto;
				}
				.text {
					font-weight: 400;
					font-size: 16px;
					// color: #262634;
				}
				.tag {
				}
			}
			.sy {
				font-size: 30px;
				margin-top: 10px;
			}
		}
		.updataItem {
			display: flex;
			flex-wrap: wrap;

			.ent_item {
				position: relative;
				top: 0px;
				left: 0px;
				margin-right: 20px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				min-width: 150px;
				border: 1px solid #262634;
				padding: 15px 5px;
				border-radius: 4px;
				margin-bottom: 10px;
				width: 200px;
				height: 64px;
				.text {
					font-weight: 400;
					font-size: 16px;
				}
				.icon {
					position: absolute;
					top: -5px;
					right: -5px;
					background-color: red;
					border-radius: 50%;
					color: white;
				}
				.box_item {
					.icon_box {
						position: relative;
						display: inline-block;
						left: 50%;
						margin-left: -40px;
						.icon {
							width: 30px;
							height: 30px;
							position: absolute;
							top: -15px;
							right: -15px;
							background-color: white;
							border: 1px solid #d7d7d7;
							border-radius: 50%;
							cursor: pointer;
						}
						.img {
							width: 80px;
							height: 80px;
							border: 1px solid #999999;
							border-radius: 5px;
							font-size: 45px !important;
							justify-content: center;
							margin: auto;
						}
					}
				}
			}
			.ent_item_add {
				cursor: pointer;
				height: 55px;
				width: 200px;
				height: 64px;
				border: 1px dotted #c0c0c0;
				border-radius: 10px;
				background-color: #fafafa;
			}
		}
	}

	.box_bottom {
		display: flex;
		justify-content: space-between;
		align-items: stretch;
		.left {
			margin-right: 20px;
			width: 38%;
			height: 100%;
			.content_left {
				padding: 0px 20px;
				width: 100%;
				.item {
					padding: 25px 0px;
					width: 100%;
					box-shadow: 0px 3px 8px 0px rgba(0, 0, 0, 0.16);
					border-radius: 4px 4px 4px 4px;
					text-align: center;
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20px;
					background-color: #f6f9fe;
					.home_img {
						width: 120px;
						height: 185px;
						margin-left: 20px;
					}
					.text {
						font-weight: 400;
						font-size: 28px;
						color: #666666;
						.num {
							font-weight: 700;
							font-size: 56px;
							color: #4655f5;
							margin: 5px;
						}
					}
					.data {
						margin-right: 20px;
						margin-top: 15px;
						font-size: 25px;
						color: #666666;
						cursor: pointer;
					}
					.data :hover {
					}
				}
			}
		}
		.right {
			flex: 1;
			height: 100%;
			.content_right {
				width: 100%;
				height: 510px;
				overflow: auto;
				.item {
					padding: 20px 20px;
					border-top: 1px solid#EBEBEB;
					border-bottom: 1px solid#EBEBEB;
					display: flex;
					justify-content: space-between;
					align-items: center;
					cursor: pointer;
					.left {
						width: 10px;
						height: 10px;
						border-radius: 50%;
						background-color: #f7af26;
					}
					.right {
						flex: 1;
						.top_le {
							font-weight: 500;
							font-size: 18px;
							color: #262634;
						}
						.top_rig {
							margin-left: 15px;
							font-size: 12px;
							border: 1px solid #828cff;
							background-color: #ebeefe;
							border-radius: 5px;
							color: #4655f5;
							padding: 2px 5px;
						}
						.time {
							font-size: 15px;
							margin-top: 8px;
							color: #aaaaaa;
						}
					}
				}
			}
		}
	}
}
</style>
